package Box2D.Dynamics.Controllers
{
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Common.Math.b2Vec3;
	import Box2D.Common.b2Color;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2DebugDraw;
	import Box2D.Dynamics.b2TimeStep;
	
	import flash.geom.Point;

	public class b2FrictionController extends b2Controller
	{
		public var useWorldGravity:Boolean = false;
		public var gravity:b2Vec2 = null;
		private var VelocityBase:Number = 0.06; 
		
		public function b2FrictionController()
		{
			super();
		}
		public override function Step(step:b2TimeStep):void
		{
			if(!m_bodyList)
				return;
			if(useWorldGravity){
				gravity = GetWorld().GetGravity().Copy();
			}
			for(var i:b2ControllerEdge=m_bodyList;i;i=i.nextBody){
				var body:b2Body = i.body;
				if(body.IsAwake() == false){
					continue;
				}
				var vec2:b2Vec2  = body.GetLinearVelocity();
				var len:Number = vec2.Length();
				if (len < VelocityBase)
				{
					vec2.SetZero();
				}
				else{
				vec2.x -= VelocityBase * vec2.x / len;
				vec2.y -= VelocityBase * vec2.y / len;
				}
				body.SetLinearVelocity(vec2)
			}
		}
		
		public var normal:b2Vec2 = new b2Vec2(0,-1);
		public var offset:Number = 0;
		public override function Draw(debugDraw:b2DebugDraw):void
		{
			var r:Number = 1000;
			//Would like to draw a semi-transparent box
			//But debug draw doesn't support that
			var p1:b2Vec2 = new b2Vec2();
			var p2:b2Vec2 = new b2Vec2();
			p1.x = normal.x * offset + normal.y * r;
			p1.y = normal.y * offset - normal.x * r;
			p2.x = normal.x * offset - normal.y * r;
			p2.y = normal.y * offset + normal.x * r;
			var color:b2Color = new b2Color(0,0,1);
			debugDraw.DrawSegment(p1,p2,color);
		}
	}
}